package com.bupt.kgplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bupt.kgplatform.Util.PageInfo;
import com.bupt.kgplatform.Util.R;
import com.bupt.kgplatform.Util.RedisCache;
import com.bupt.kgplatform.entity.User;
import com.bupt.kgplatform.entity.pojo.LoginInfo;
import com.bupt.kgplatform.entity.pojo.QueryUserReq;
import com.bupt.kgplatform.entity.pojo.UserList;
import com.bupt.kgplatform.mapper.UserMapper;
import com.bupt.kgplatform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhuyunfei
 * @since 2022-11-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserMapper userMapper;
    @Override
    public R login(LoginInfo loginInfo){
        String userName = loginInfo.getUserName();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userName);
        Long l = userMapper.selectCount(queryWrapper);
        if(l == 0){
            return R.failure("用户不存在");
        }else{
            User user = userMapper.selectOne(queryWrapper);
            if(user.getPwd().equals(loginInfo.getPwd())){

                String token = UUID.randomUUID().toString();
                // token是键，用户id是值
                redisCache.setCacheObject(token, user.getId(), 1, TimeUnit.DAYS);
                return R.ok(user, token);
            }else{
                return R.failure("账号或密码错误");
            }
        }

    }

    @Override
    public R getAllUser(){

        List<User> users = userMapper.selectList(null);
        List<UserList> userList = new ArrayList<>();
        for (User user : users){
            UserList user1= new UserList(user.getId(), user.getUserName());
            userList.add(user1);
        }
        return R.ok(userList);
    }


    public R QueryUser(QueryUserReq queryUserReq){
        Page<User> page = new Page<>(queryUserReq.getPageNo(), queryUserReq.getPageSize());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        queryWrapper.like(StringUtils.isNotBlank(queryUserReq.getQueryInfo().getUserName()), "user_name", queryUserReq.getQueryInfo().getUserName());
        queryWrapper.like(StringUtils.isNotBlank(queryUserReq.getQueryInfo().getPhoneNumber()), "phone_number", queryUserReq.getQueryInfo().getPhoneNumber());

        PageInfo pageInfo = new PageInfo(page);
        return R.ok(page.getRecords(), pageInfo);
    }

}
